package com.handwriting.backend.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.handwriting.backend.entity.User;
import com.handwriting.backend.exceptions.PasswordException;
import com.handwriting.backend.exceptions.UserAlreadyExistsException;
import com.handwriting.backend.exceptions.UserNotFoundException;
import com.handwriting.backend.mapper.UserMapper;
import com.handwriting.backend.message.UserInfo;
import com.handwriting.backend.utils.TokenUtils;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class UserService {
    private final UserMapper mapper;

    public UserService(UserMapper mapper) {
        this.mapper = mapper;
    }

    public String login(String username, String password) throws UserNotFoundException {
        List<User> users = mapper.selectList(new QueryWrapper<User>().eq("username", username));
        if (users.isEmpty()) {
            throw new UserNotFoundException("No user named " + username + ".");
        }
        User user = users.get(0);
        if (!user.getRole().equals("admin")) {
            throw new UserNotFoundException("No user named " + username + ".");
        }
        if (password.equals(user.getPassword())) {
            return TokenUtils.generateToken(username);
        } else {
            throw new PasswordException("Password is error.");
        }
    }

    public void register(String username, String password, String role) {
        long cnt = mapper.selectCount(new QueryWrapper<User>().eq("username", username));
        if (cnt > 0) {
            throw new UserAlreadyExistsException("User named " + username + "has been registered.");
        }
        mapper.insert(new User(0, username, password, role));
    }

    public void deleteUser(int id) {
        int n = mapper.deleteById(id);
    }

    public User getUser(String username) {
        List<User> users = mapper.selectList(new QueryWrapper<User>().eq("username", username));
        return users.get(0);
    }

    public List<UserInfo> getUsers() {
        List<User> users = mapper.selectList(null);
        return users.stream().map(user -> new UserInfo(user.getId(), user.getUsername(), user.getRole())).toList();
    }

    public void updateUser(UserInfo userInfo) throws UserNotFoundException {
        User user = new User();
        user.setId(userInfo.getId());
        user.setUsername(userInfo.getUsername());
        user.setRole(user.getRole());
        long n = mapper.selectCount(new QueryWrapper<User>().eq("id", userInfo.getId()));
        if (n == 0) {
            throw new UserNotFoundException("User Not Found");
        }
        mapper.updateById(user);
    }
}
